import React, {Component} from 'react'
import Loading from './loading'

export default (loadComponent, placeholder = '拼命加载中...', props = {}) => {
  return class AsyncComponent extends Component {
    unmount = false

    constructor(props) {
      super(props)
      this.state = {
        Child: null
      }
    }

    componentWillUnmount() {
      this.unmount = true
    }

    async componentDidMount() {
      try {
        const {default: Child} = await loadComponent()
        if (this.unmount) return
        this.setState({
          Child
        })
      } catch (err) {
        console.error(err)
      }
    }

    render() {
      const {Child} = this.state
      return (
        Child
          ? <Child {...props} {...this.props} />
          : <Loading />
      )
    }
  }
}